'use strict';

const Controller = require('egg').Controller;
const user_list = [
    {id:1,name:'张飞',age:56},
    {id:2,name:'马超',age:65},
    {id:3,name:'赵云',age:34}
];

class UsersController extends Controller {
    //显示用户列表
    async index (){
        const { ctx } = this;
        await ctx.render("index");
    }

    //显示添加页面
    async toAdd(){
        

    }

    //显示编辑页
    async toEdit(){

    }

    //发送用户列表
    async showList(){
        this.ctx.body = {
            code:2000,
            msg:'ok',
            data:user_list
        };
    }

    //保存用户信息，存在id且大于0时为编辑，否则为添加
    async saveUser(){
        let user = this.ctx.request.body;
        let isUpdate = user.id > 0 ? true : false;
        if(!isUpdate){
            user.id = this.getId();
            user_list.push(user);
        }else{
            for(var i=0;i<user_list.length;i++){
                if(user.id == user_list[i]['id']){
                    user_list.splice(i,1,user);
                    break;
                }
            }
        }
        this.ctx.body = {
            code:2000,
            msg:'保存成功',
            data:user_list
        };
    }

    //删除用户
    async delUser(){
        let id = this.ctx.params.id;
        for(var i=0;i<user_list.length;i++){
            if(id == user_list[i]['id']){
                user_list.splice(i,1);
                this.ctx.body = {
                    code:2000,
                    msg:'删除成功',
                    data:user_list
                };
                return;
            }
        }
        this.ctx.body = {
            code:4000,
            msg:"删除失败",
            data:user_list
        };
    }

    //登录
    async login(){
        let info = this.ctx.request.body;
        if(info.userName == "admin" && info.userPwd == "123123"){
            let token = this.app.jwt.sign(info,this.app.config.jwt.secret);
            this.ctx.body = {
                code:2000,
                msg:'登录成功',
                data:token
            };
        }else{
            this.ctx.body = {
                code:4000,
                msg:'账户名或密码错误',
                data:info
            };
        }
    }

    getId(){
        let id = 0;
        for(var i=0;i<user_list.length;i++){
            id = user_list[i]['id'] > id ? user_list[i]['id'] : id;
        }
        return ++id;
    }
}

module.exports = UsersController;